package org.starapp.rbac.rest;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * @author 王强
 *修改
 */
public class RestPost {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			// TODO Auto-generated method stub
			DefaultHttpClient httpclient = new DefaultHttpClient();
			// 代理的设置  
//			HttpHost proxy = new HttpHost("192.168.1.2", 8888);
//			httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
//					proxy);
			// 目标地址  
			HttpPost httppost = new HttpPost(
					"http://localhost:8888/starapp-demo/api/v1/users");
			System.out.println("请求: " + httppost.getRequestLine());
			// 构造最简单的字符串数据  
			StringEntity reqEntity = new StringEntity("{\"userId\": \"admin\",\"userName\": \"hedi\"}");
			
			
//			//组装数据放到HttpEntity中发送到服务器  
//			final List dataList = new ArrayList();  
//			dataList.add(new BasicNameValuePair("productName", "cat"));  
//			dataList.add(new BasicNameValuePair("price", "14.87"));  
//			HttpEntity entity = new UrlEncodedFormEntity(dataList, "UTF-8");  
//			httpPost.setEntity(entity);  
			
			
			
			// 设置类型  
			reqEntity.setContentType("application/json");
			// 设置请求的数据  
			httppost.setEntity(reqEntity);
			// 执行  
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			System.out.println("----------------------------------------");
			System.out.println(response.getStatusLine());
			if (entity != null) {
				System.out.println("Response content length: "
						+ entity.getContentLength());
			}
			// 显示结果  
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent(), "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
			if (entity != null) {
				entity.consumeContent();
			}
			httpclient.getConnectionManager().shutdown();
		} catch (Exception e) {
			// TODO: handle exception
		}  
	}

}
